package one.stand.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import com.jmp.api.admin.dto.BusinessCardAuthSaveRequest;
import com.jmp.api.admin.dto.BusinessCardInfoRequest;
import com.jmp.api.admin.dto.BusinessCardInfoResponse;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.SecurityUserApi;
import com.jmp.base.dto.*;
import com.jmp.feign.SecurityUserFeign;
import com.jmp.feign.SunCodeFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.dto.Company2Dto;
import one.stand.dto.ConvertUtils;
import one.stand.entity.excel.BusinessExcelEntity;
import one.stand.model.BusinessCard;
import one.stand.model.ResultModel;
import one.stand.request.BusinessCardRequest;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.util.AssertUtil;
import one.stand.util.ExcelUtil;
import one.stand.util.ExportDataDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @author: ZRH
 * @CreateDate: 2019/4/17 9:45
 */
@RestController
@RequestMapping("adminApi/businessCard")
@Api(description = "用户管理")
@Slf4j
public class BusinessCardController extends BaseController {

    @Autowired
    private SecurityUserFeign securityUserFeign;
    @Autowired
    private SunCodeFeign sunCodeFeign;

    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private CompanyBaseService companyBaseService;

    @ApiOperation(value = "1查询用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userType", value = "null为所有   1普通用户  2企业所属人", paramType = "Integer"),
            @ApiImplicitParam(name = "name", value = "条件查询", paramType = "String"),
    })
    @PostMapping("selectCustomerList")
    @SecurityAuthCheck
    public ResultModel<Map<String, Object>> selectCustomerList(BusinessCardRequest request) {
        return adminFegin.selectCustomerList(request);
    }

    @ApiOperation(value = "1导出用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userType", value = "null为所有  1普通用户  2企业所属人", paramType = "Integer"),
            @ApiImplicitParam(name = "name", value = "条件查询", paramType = "String"),
    })
    @PostMapping("selectCustomerListExport")
    @SecurityAuthCheck
    public void selectCustomerListExport(BusinessCardRequest request, HttpServletResponse response) {
        ResultModel<ExportDataDTO<BusinessExcelEntity>> resultModel = adminFegin.selectCustomerListExport(request);
        if (resultModel.getCode().equals(ResultEnum.SUCCESS.getCode())) {
            ExportDataDTO file = resultModel.getData();
            try {
                ExcelUtil.exportExcel(file, BusinessExcelEntity.class, response);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @ApiOperation(value = "2用户信息")
    @GetMapping("info")
    @SecurityAuthCheck
    public ResultModel<BusinessCardInfoResponse> getCustomerInfo(BusinessCardInfoRequest request) {

        BusinessCard card = businessCardBaseService.getCustomer(request.getCardId());
        AssertUtil.isTrue(Objects.nonNull(card) && card.getIsDel() == 0, ResultEnum.PARAM_CHECK, "名片不存在");
        Company2Dto company2Dto = companyBaseService.get2(card.getCompanyId());
        SunCodeCardRequest sunCodeCardRequest = SunCodeCardRequest.builder().cardId(request.getCardId()).build();
        ResultModel<SunCodeCardResponse> sunCodeCardResponseResultModel = sunCodeFeign.card(sunCodeCardRequest);
        AssertUtil.isTrue(sunCodeCardResponseResultModel);

        ResultModel<SecurityAuthListVo> securityAuthListVoResultModel = securityUserFeign.authList(SecurityAuthListDto.builder()
                .type(SecurityUserApi.AUTH_USER_TYPE_CARD)
                .typeId(request.getCardId())
                .build());
        AssertUtil.isTrue(securityAuthListVoResultModel);

        BusinessCardInfoResponse response = BusinessCardInfoResponse.builder()
                .logo(card.getLogo())
                .name(card.getName())
                .phone(card.getPhone())
                .personalWx(card.getPersonalWx())
                .soundRecording(card.getSoundRecording())
                .position(card.getPosition())
                .seeNum(card.getSeeNum())
                .createTime(card.getCreateTime().getTime())
                .briefIntroduction(card.getBriefIntroduction())
                .photo(StrUtil.split(card.getPhoto(), CharUtil.COMMA))
                .companyName(company2Dto.getCompanyName())
                .wxTwoCode(sunCodeCardResponseResultModel.getData().getCodeUrl())
                .authList(ConvertUtils.list(securityAuthListVoResultModel.getData().getAuthList(), auth -> {
                    return BusinessCardInfoResponse.Auth.builder()
                            .typeAuthName(auth.getTypeAuthName())
                            .typeAuth(auth.getTypeAuth())
                            .authCheck(auth.getAuthCheck())
                            .id(auth.getId())
                            .startTime(auth.getStartTime())
                            .endTime(auth.getEndTime())
                            .build();
                }))
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3用户权限：保存")
    @PostMapping("auth/save")
    @SecurityAuthCheck
    public ResultModel authSave(@RequestBody BusinessCardAuthSaveRequest request) {

        ResultModel<SecurityAuthSaveVo> resultModel = securityUserFeign.authSave(SecurityAuthSaveDto.builder()
                .id(request.getId())
                .type(SecurityUserApi.AUTH_USER_TYPE_CARD)
                .typeId(request.getCardId())
                .typeAuth(request.getTypeAuth())
                .startTime(DateUtil.date(request.getStartTime()))
                .endTime(DateUtil.date(request.getEndTime()))
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }
}
